
import { ElLoading, ElMessage } from 'element-plus'
import { ref, computed, watch } from 'vue'
import { login, getSelfUserInfo } from '@/api/user'
import { useUserStore } from '@/store/modules/user.js'
import appRouterManger from '@/router'

class LoginPresenter {

    loadingInstance = ref(null)
    userStore = useUserStore()

    constructor(){
        this.toLogin = this.toLogin.bind(this)
        this.toLogout = this.toLogout.bind(this)
    }
    

    async toLogin(loginInfo) {
        this.loadingInstance.value = ElLoading.service({
            fullscreen: true,
            text: '登录中，请稍候...',
        })
        var result = false
        try {
            const res = await login(loginInfo)
            if (res.code === 0) {
                this.userStore.setUserInfo(res.data.user)
                this.userStore.setUid(res.data.user.uid)
                this.userStore.setSid(res.data.sid)
                await appRouterManger.router.push({ name: "Dashboard" })
                ElMessage({
                    type: 'success',
                    message: '登录成功'
                })
                result = true
                } else {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                    showClose: true,
                })
            }
        } catch (e) {
            console.log("登录失败 " + e.message);
        }
        this.loadingInstance.value.close()
        return result
    }


    /* 登出*/
    async toLogout() {
        this.userStore.ClearStorage()
        await appRouterManger.router.push({ name: 'Login', replace: true })
    }

}

export default LoginPresenter